<template>
  <div style="width:100%;">
    <el-alert v-if="errorMsg" :title="errorMsg" type="error" show-icon style="margin-bottom: 16px;" />
    <div v-if="!loading && !errorMsg">
      <!-- 上 -->
      <el-card class="card0" style="margin-bottom: 20px;">
        <el-row :gutter="20" style="display: flex; align-items: center;">
          <!-- 时间显示 -->
          <el-col :span="6">
            <time1></time1>
          </el-col>
          <!-- 时间筛选控件 -->
          <el-col :span="18" style="text-align: right;">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
              @change="onDateChange"
              style="width: 350px;"
            />
          </el-col>
        </el-row>
      </el-card>

      <!-- 中 -->
      <el-row :gutter="20">
        <!-- 销售额 -->
        <el-col :span="6">
          <el-card class="card1">
            <template #header>
              <div class="card-header card-header-style">
                <span class="header-left">销售额</span>
                <span class="header-right"><el-icon><InfoFilled /></el-icon></span>
              </div>
            </template>
            <div>
              <div class="card-container-Title">{{ saleData.todaySale }}</div>
              <div class="card-container">
                <div>
                  <span>周环比</span>
                  <el-icon style="color: #95d475;" v-if="saleData.weekRate>0">
                    <CaretTop />
                  </el-icon>
                  <el-icon style="color: #f89898;" v-else>
                    <CaretBottom />
                  </el-icon>
                  <span>{{ absolute(saleData.weekRate) }}%</span>
                </div>
                <div>
                  <span>日环比</span>
                  <el-icon style="color: #95d475;" v-if="saleData.dayRate>0">
                    <CaretTop />
                  </el-icon>
                  <el-icon style="color: #f89898;" v-else>
                    <CaretBottom />
                  </el-icon>
                  <span>{{ absolute(saleData.dayRate) }}%</span>
                </div>
              </div>
            </div>
            <template #footer>
              <div class="card-footer">
                <span>日均销售额</span>
                <span>￥{{ absolute(saleData.average) }}</span>
              </div>
            </template>
          </el-card>
        </el-col>
        <!-- 订单数 -->
        <el-col :span="6">
          <el-card class="card1">
            <template #header>
              <div class="card-header card-header-style">
                <span class="header-left">订单数</span>
                <span class="header-right"><el-icon><InfoFilled /></el-icon></span>
              </div>
            </template>
            <OrderNumber :dateRange="dateRange" />
            <!-- <div style="text-align:center;font-size:15px;color:#73767a;margin-top:0px;">订单总数</div> -->
            <template #footer>
              <div class="card-footer">
                <!-- <span>日订单数</span> -->
                <span>{{ avgOrderCount }}</span>
              </div>
            </template>
          </el-card>
        </el-col>
        <!-- 已发货 -->
        <el-col :span="6">
          <el-card class="card1">
            <template #header>
              <div class="card-header card-header-style">
                <span class="header-left">已发货</span>
                <span class="header-right"><el-icon><InfoFilled /></el-icon></span>
              </div>
            </template>
            <div class="chart-container">
              <shipped-chart :data="shippedChartData"></shipped-chart>
            </div>
            <template #footer>发货率：{{ deliveryRate.toFixed(2) }} %</template>
          </el-card>
        </el-col>
        <!-- 已评价 -->
        <el-col :span="6">
          <el-card class="card1">
            <template #header>
              <div class="card-header card-header-style">
                <span class="header-left">已评价</span>
                <span class="header-right"><el-icon><InfoFilled /></el-icon></span>
              </div>
            </template>
            <div style="font-size:18px;margin-bottom:8px;">评价率：{{ commentRate }}%</div>
            <comment-number :dateRange="dateRange"></comment-number>
          </el-card>
        </el-col>
      </el-row>

      <!-- 下 -->
      <!-- 销售额趋势 -->
      <el-row :gutter="24">
        <el-col :span="18">
          <el-card class="card2">
            <template #header>
              <div class="card-header card-header-style" style="color: #303133;">
                <span>销售额</span>
              </div>
            </template>
            <span>销售额趋势</span>
            <SaleChart :data="saleChartData" />
          </el-card>
        </el-col>

        <!-- 热门商品 -->
        <el-col :span="6">
          <el-card class="card3">
            <template #header>
              <div class="card-header">
                <span style="font-weight: bold; font-size: 20px">热门商品</span>
              </div>
            </template>
            <!-- 热门商品组件 -->
            <hot-product :dateRange="dateRange"></hot-product>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted, nextTick } from 'vue';
import SaleChart from '@/components/SalesChart.vue';
import OrderNumber from '@/components/OrderNumber.vue';
import { getDaySale } from'../api/order'
import { ElMessage } from "element-plus";

const deliveryRate = ref(0) //发货率
const loading = ref(true);
const hot = ref()
const saleData=ref([]);
const shipped = ref();
const dateRange = ref([])
const shortcuts = [
  {
    text: '今日',
    value: () => {
      const start = new Date();
      const end = new Date();
      return [start, end];
    },
  },
  {
    text: '近7天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(end.getDate() - 6);
      return [start, end];
    },
  },
  {
    text: '近30天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(end.getDate() - 29);
      return [start, end];
    },
  },
  {
    text: '本月',
    value: () => {
      const end = new Date();
      const start = new Date(end.getFullYear(), end.getMonth(), 1);
      return [start, end];
    },
  },
];

const errorMsg = ref('');
const saleChartData = ref([]);
const shippedChartData = ref([]);
const totalOrderCount = ref(0);
const commentRate = ref('0.00');

onBeforeMount(() => {
  const hot=ref()
})

onMounted(() => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    const end = new Date();
    const start = new Date();
    start.setDate(end.getDate() - 6);
    dateRange.value = [start, end];
  }
  getTodayDaySale();
  nextTick(() => {
    setTimeout(() => {
      onDateChange(); // 保证子组件已挂载并自动加载热门商品
    }, 0);
  });
})

function getDateRangeArray(start, end) {
  const arr = [];
  let dt = new Date(start);
  const endDt = new Date(end);
  while (dt <= endDt) {
    arr.push(dt.toISOString().slice(0, 10));
    dt.setDate(dt.getDate() + 1);
  }
  return arr;
}

const getTodayDaySale = () => {
  if (!Array.isArray(dateRange.value) || dateRange.value.length !== 2) return;
  const [start, end] = dateRange.value;
  getDaySale().then(resp => {
    const result = resp.data;
    if (result.code === 200 && Array.isArray(result.data)) {
      const formatDate = d => {
        const date = new Date(d);
        return date.toISOString().slice(0, 10);
      };
      const startStr = formatDate(start);
      const endStr = formatDate(end);
      // 1. 生成区间所有日期
      const allDays = getDateRangeArray(startStr, endStr);
      // 2. 转成map方便查找
      const dataMap = {};
      result.data.forEach(d => { dataMap[d._id] = d; });
      // 3. 补全区间内所有天
      const fullData = allDays.map(day => ({
        _id: day,
        totalAmount: dataMap[day]?.totalAmount || 0,
        count: dataMap[day]?.count || 0
      }));
      saleChartData.value = fullData;
      // 统计区间销售额
      const total = fullData.reduce((sum, d) => sum + (d.totalAmount || 0), 0);
      const days = fullData.length;
      const average = days > 0 ? (total / days).toFixed(2) : 0;
      // 日环比
      let dayRate = 0;
      if (fullData.length > 1 && fullData[fullData.length - 2].totalAmount !== 0) {
        const last = fullData[fullData.length - 1].totalAmount;
        const prev = fullData[fullData.length - 2].totalAmount;
        dayRate = (((last - prev) / prev) * 100).toFixed(2);
      }
      // 周环比（区间环比）
      let weekRate = 0;
      const allSorted = result.data.sort((a, b) => a._id.localeCompare(b._id));
      const startIdx = allSorted.findIndex(d => d._id === startStr);
      if (startIdx >= days) {
        const prevRange = allSorted.slice(startIdx - days, startIdx);
        const prevTotal = prevRange.reduce((sum, d) => sum + (d.totalAmount || 0), 0);
        if (prevTotal !== 0) {
          weekRate = (((total - prevTotal) / prevTotal) * 100).toFixed(2);
        }
      }
      saleData.value = {
        todaySale: total,
        average: average,
        weekRate: isNaN(weekRate) ? 0 : weekRate,
        dayRate: isNaN(dayRate) ? 0 : dayRate
      };
      loading.value = false;
    } else {
      errorMsg.value = result.message || '获取日销售额失败';
      ElMessage.error(errorMsg.value)
      loading.value = false;
    }
  }).catch(error => {
    errorMsg.value = '获取日销售额失败: ' + (error.message || error);
    ElMessage.error(errorMsg.value)
    console.error(errorMsg.value, error)
    loading.value = false;
  });
};

const getOrderCount = () => {
  import('@/api/order').then(module => {
    module.getOrderCountByDateRange({ dateRange: dateRange.value }).then(res => {
      totalOrderCount.value = res.data.totalCount || 0;
      // 计算发货率
      const shippedCount = shippedChartData.value.reduce((sum, d) => sum + (d.count || 0), 0);
      deliveryRate.value = totalOrderCount.value > 0 ? (shippedCount / totalOrderCount.value * 100) : 0;
    });
  });
};

const getShippedData = () => {
  if (!Array.isArray(dateRange.value) || dateRange.value.length !== 2) return;
  const [start, end] = dateRange.value;
  import('@/api/order').then(module => {
    module.getDayShipped({ dateRange: [start, end] }).then(res => {
      const result = res.data;
      if (result.code === 200 && Array.isArray(result.data)) {
        const formatDate = d => {
          const date = new Date(d);
          return date.toISOString().slice(0, 10);
        };
        const startStr = formatDate(start);
        const endStr = formatDate(end);
        const allDays = getDateRangeArray(startStr, endStr);
        const dataMap = {};
        result.data.forEach(d => { dataMap[d._id] = d; });
        const fullData = allDays.map(day => ({
          _id: day,
          count: dataMap[day]?.count || 0
        }));
        shippedChartData.value = fullData;
        // 计算发货率（已发货数/总订单数）
        const shippedCount = fullData.reduce((sum, d) => sum + (d.count || 0), 0);
        deliveryRate.value = totalOrderCount.value > 0 ? (shippedCount / totalOrderCount.value * 100) : 0;
      }
    });
  });
};

const getCommentRate = () => {
  import('@/api/order').then(module => {
    module.getCommentRateByDateRange({ dateRange: dateRange.value }).then(res => {
      commentRate.value = res.data.rate || '0.00';
    });
  });
};

/**获取数据绝对值 */
const absolute=(val)=>{
  if (val === -10000) {
    return '-';
  } else {
    return Math.abs(val);
  }
}

function onDateChange() {
  if (Array.isArray(dateRange.value) && dateRange.value.length === 2) {
    if (hot.value && typeof hot.value.method === 'function') {
      hot.value.method(null, dateRange.value);
    }
    getShippedData();
    getOrderCount();
    getTodayDaySale();
    getCommentRate();
  } else {
    console.warn('日期范围参数不完整');
  }
}

</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.card0 {
  width: 100%;
  height: 60px;
}

.card1 {
  height: 260px;
  padding: 5px 20px;
}

.card2 {
  width: 100%;
  height: 400px;
}

.card3 {
  width: 100%;
  height: 400px;
}

.card-header-style {
  color: #73767a;
  display: flex;
  align-items: center;
  height: 20px;
  justify-content: space-between;
  font-size: 15px;
}

.card-container-Title {
  font-size: 35px;
  padding-bottom: 15px;
}

.card-container {
  font-size: 15px;
  color: #73767a;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 0px;

  div {
    span:first-child {
      padding-right: 8px;
    }

    span:last-child {
      padding-left: 3px;
      font-size: 14px;
      color: black;
    }
  }
}

.card-footer {
  font-size: 15px;

  span:first-child {
    padding-right: 8px;
  }
}

:deep(.el-card__body){
  padding: 0px;
}

:deep(.el-card__header){
  padding-left: 15px;
  padding-right: 15px;
}
</style>